use hyper::{Body, Request, Response};
use wd_run::Context;

pub struct HtpLogMiddle;

#[async_trait::async_trait]
impl super::HttpHandle for HtpLogMiddle {
    async fn request(
        &self,
        ctx: Context,
        req: Request<Body>,
    ) -> Result<Request<Body>, Response<Body>> {
        let host = if let Some(host) = req.headers().get("Host") {
            if let Ok(s) = host.to_str() {
                s.to_string()
            } else {
                String::from("host not find")
            }
        } else {
            String::from("host not find")
        };
        ctx.set("hlp_log_method", req.method().to_string()).await;
        ctx.set("hlp_log_url", req.uri().to_string()).await;
        ctx.set("hlp_log_host", format!("{:?}", host)).await;
        ctx.set("hlp_log_version", format!("{:?}", req.version()))
            .await;
        Ok(req)
    }
    async fn response(&self, ctx: Context, resp: Response<Body>) -> Response<Body> {
        let name = ctx.get::<_, String>("application_name").await.unwrap();
        let method = ctx.get::<_, String>("hlp_log_method").await.unwrap();
        let url = ctx.get::<_, String>("hlp_log_url").await.unwrap();
        let host = ctx.get::<_, String>("hlp_log_host").await.unwrap();
        let version = ctx.get::<_, String>("hlp_log_version").await.unwrap();
        wd_log::log_info_ln!(
            "RetryPoint[{}] ---> version:{} method:{} host:{} url:{} response_status:{}",
            name.as_str(),
            version.as_str(),
            method.as_str(),
            host.as_str(),
            url.as_str(),
            resp.status().as_str()
        );
        resp
    }
}
